package com.zhilianbao.leyaogo.view.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bql.utils.CheckUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.utils.Utils;

import java.util.List;

/**
 * Create by Cyarie
 */
public class TagGroup extends ViewGroup {

    private static final String TAG = TagGroup.class.getSimpleName();
    private static final int TYPE_TEXT_NORMAL = 1;
    private List<String> tags;
    private LayoutInflater mInflater;
    private OnTagClickListener onTagClickListener;
    private int sizeWidth;
    private int sizeHeight;
    private int mTagBorderHor;
    private int mTagBorderVer;
    private int mTagResId;
    private boolean mCanTagClick;
    private static final int DEFAULT_TEXT_BORDER_HORIZONTAL = 10;
    private static final int DEFAULT_TEXT_BORDER_VERTICAL = 8;
    private static final int DEFAULT_TAG_RES_ID = R.layout.item_tag_default;
    private static final boolean DEFAULT_CAN_TAG_CLICK = true;

    public TagGroup(Context context) {
        this(context, null);
    }

    public TagGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TagGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mInflater = LayoutInflater.from(context);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.TagGroup,
                defStyleAttr,
                defStyleAttr
        );

        mTagBorderHor = a.getDimensionPixelSize(
                R.styleable.TagGroup_tg_itemBorderHorizontal, Utils.dp2px(DEFAULT_TEXT_BORDER_HORIZONTAL));
        mTagBorderVer = a.getDimensionPixelSize(
                R.styleable.TagGroup_tg_itemBorderVertical, Utils.dp2px(DEFAULT_TEXT_BORDER_VERTICAL));
        mCanTagClick = a.getBoolean(R.styleable.TagGroup_tg_canTagClick, DEFAULT_CAN_TAG_CLICK);
        mTagResId = a.getResourceId(R.styleable.TagGroup_tcvTagResId, DEFAULT_TAG_RES_ID);
        a.recycle();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return (!mCanTagClick) || super.onInterceptTouchEvent(ev);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
    }

    /**
     * 计算 ChildView 宽高
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @SuppressLint("DrawAllocation")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 计算 ViewGroup 上级容器为其推荐的宽高
         */
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        //计算 childView 宽高
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        int totalWidth = 0;
        int totalHeight = 0;
        totalHeight = getMultiTotalHeight(totalWidth, totalHeight);

        /**
         * 高度根据设置改变
         * 如果为 MATCH_PARENT 则充满父窗体，否则根据内容自定义高度
         */
        setMeasuredDimension(
                sizeWidth,
                (heightMode == MeasureSpec.EXACTLY ? sizeHeight : totalHeight));

    }


    /**
     * 为 multiLine 模式布局，并计算视图高度
     *
     * @param totalWidth
     * @param totalHeight
     * @return
     */
    private int getMultiTotalHeight(int totalWidth, int totalHeight) {
        int childWidth;
        int childHeight;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            childWidth = child.getMeasuredWidth();
            childHeight = child.getMeasuredHeight();

            totalWidth += childWidth;

            if (i == 0) {
                totalHeight = childHeight;
            }
            if (totalWidth + mTagBorderHor > sizeWidth) {
                totalWidth = 0;
                totalHeight += childHeight + mTagBorderVer;
                child.layout(
                        totalWidth,
                        totalHeight - childHeight,
                        totalWidth + childWidth,
                        totalHeight);
                totalWidth += childWidth + mTagBorderHor;
            } else {
                child.layout(
                        totalWidth - childWidth,
                        totalHeight - childHeight,
                        totalWidth,
                        totalHeight);
                totalWidth += mTagBorderHor;
            }
        }
        return totalHeight;
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return super.generateLayoutParams(attrs);
    }

    public void setTags(List<String> tagList) {
        this.tags = tagList;
        this.removeAllViews();
        if (tags != null && tags.size() > 0) {
            for (int i = 0; i < tags.size(); i++) {
                TextView tagView = (TextView) mInflater.inflate(mTagResId, null);
                LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                tagView.setLayoutParams(layoutParams);
                if (!CheckUtils.isEmpty(tags.get(i)) && tags.get(i).length() > 10) {
                    String subStr = tags.get(i).substring(0, 10) + "…";
                    tagView.setText(subStr);
                } else {
                    tagView.setText(tags.get(i));
                }

                tagView.setTag(TYPE_TEXT_NORMAL);
                final int finalI = i;
                tagView.setOnClickListener(v -> {
                    if (onTagClickListener != null) {
                        onTagClickListener.onTagClick(finalI, tags.get(finalI));
                    }
                });
                addView(tagView);
            }
        }
        postInvalidate();
    }


    public void setOnTagClickListener(OnTagClickListener onTagClickListener) {
        this.onTagClickListener = onTagClickListener;
    }

    public interface OnTagClickListener {
        void onTagClick(int position, String text);
    }

    public List<String> getTags() {
        return tags;
    }
}
